// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init();
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const { collection, query = {}, projection } = event;
  
  try {
    // 从指定集合获取数据
    let dbQuery = db.collection(collection).where(query);
    
    // 如果提供了projection参数，只返回指定字段
    if (projection && typeof projection === 'object') {
      dbQuery = dbQuery.field(projection);
    }
    
    const result = await dbQuery.get();
    
    return {
      success: true,
      data: result.data,
      openid: wxContext.OPENID,
      appid: wxContext.APPID,
    };
  } catch (error) {
    return {
      success: false,
      error: error.message
    };
  }
};